package cn.bisoft.java.util.common;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.InvalidResultSetAccessException;
import org.springframework.jdbc.support.rowset.SqlRowSet;

import cn.bisoft.java.service.dao.EntityConfig;
import cn.bisoft.java.util.config.ConfigProvider;
import cn.bisoft.java.util.config.ConfigProviderFactory;

public class SQLUtil
{

	public final static String JDBC_CONFIG_PATH = "entity-config.xml";

	private static final Log logger = LogFactory.getLog(SQLUtil.class);

	public static final int ENTITY_COUNT = 4;

	public static final int ENTITY_DELETE = 3;

	public static final int ENTITY_INSERT = 1;

	public static final int ENTITY_SAVE_OR_UPDATE = 5;

	public static final int ENTITY_SELECT_FOR_UPDATE = 6;

	public static final int ENTITY_SELECT = 0;

	public static final int ENTITY_UPDATE = 2;

	@SuppressWarnings("unchecked")
	public static Map<String, EntityConfig> getEntityMap()
	{
		ConfigProvider cp = ConfigProviderFactory.getInstance(SQLUtil.JDBC_CONFIG_PATH, EntityConfig.class);
		return (Map<String, EntityConfig>) cp.getAllConfig();
	}

	public static String createInsertStatement(EntityConfig dc, Object entity) throws Exception
	{
		try
		{
			StringBuffer fieldStr = new StringBuffer(" ( ");
			StringBuffer valueStr = new StringBuffer(" ( ");
			Method[] methods = entity.getClass().getMethods();
			SimpleDateFormat timeStampFormt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
			for (int i = 0; i < methods.length; i++)
			{
				Method method = methods[i];
				String fieldName = method.getName().substring(3);
				if ((!method.getDeclaringClass().equals(Object.class)) && (method.getName().startsWith("get")))
				{
					Class<?> rtnType = method.getReturnType();
					Object value = method.invoke(entity);
					if (value != null)
					{
						if (rtnType.equals(java.lang.String.class))
						{
							fieldStr.append(" ").append(fieldName).append(",");
							valueStr.append(" '").append(value.toString()).append("',");
						}
						else if (rtnType.equals(java.util.Date.class))
						{
							fieldStr.append(" ").append(fieldName).append(",");
							valueStr.append(" '").append(timeStampFormt.format((Date) value)).append("',");
						}
						else
						{
							fieldStr.append(" ").append(fieldName).append(",");
							valueStr.append(" ").append(value.toString()).append(",");
						}
					}
				}
			}
			fieldStr = fieldStr.deleteCharAt(fieldStr.length() - 1);
			valueStr = valueStr.deleteCharAt(valueStr.length() - 1);
			valueStr.append(" ) ");
			fieldStr.append(" ) ").append(" VALUES ").append(valueStr);
			return fieldStr.toString();
		}
		catch (Exception e)
		{
			throw new Exception(e);
		}
	}

	/**
	 * <pre>
	 * �����������
	 * </pre>
	 * @param dc ������
	 * @param entity ʵ�����
	 * @return ��������
	 */
	public static String createKeyStatement(EntityConfig dc, Class<?> entity, String entityId) throws Exception
	{
		try
		{
			String getName = "get" + dc.getPrimaryKey().substring(0, 1).toUpperCase() + dc.getPrimaryKey().substring(1);
			Method method = entity.getMethod(getName);
			Class<?> keyType = method.getReturnType();
			if (keyType.equals(java.lang.String.class))
			{
				return "'" + entityId + "'";
			}
			else
			{
				return entityId;
			}
		}
		catch (SecurityException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
		catch (IllegalArgumentException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
		catch (NoSuchMethodException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
	}

	public static Object getEntityPrimaryKeyValue(EntityConfig dc, Object entity) throws Exception
	{
		String getMethod = "get" + dc.getPrimaryKey().substring(0, 1).toUpperCase() + dc.getPrimaryKey().substring(1);
		try
		{
			Method method = entity.getClass().getMethod(getMethod);
			return method.invoke(entity);
		}
		catch (SecurityException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
		catch (NoSuchMethodException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
		catch (IllegalArgumentException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
		catch (IllegalAccessException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
		catch (InvocationTargetException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
	}

	/**
	 * <pre>
	 * �����������
	 * </pre>
	 * @param dc ������
	 * @param entity ʵ�����
	 * @return ��������
	 */
	public static String createKeyStatement(EntityConfig dc, Object entity) throws Exception
	{
		String getMethod = "get" + dc.getPrimaryKey().substring(0, 1).toUpperCase() + dc.getPrimaryKey().substring(1);
		try
		{
			Method method = entity.getClass().getMethod(getMethod);
			Object keyValue = method.invoke(entity);
			if (method.getReturnType().equals(java.lang.String.class))
			{
				return "'" + keyValue.toString() + "'";
			}
			else
			{
				return keyValue.toString();
			}
		}
		catch (SecurityException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
		catch (NoSuchMethodException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
		catch (IllegalArgumentException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
		catch (IllegalAccessException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
		catch (InvocationTargetException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
	}

	/**
	 * <pre>
	 * ���SQL���
	 * </pre>
	 * @param dc ������
	 * @param entity ʵ������
	 * @param method ��ɾ�Ĳ�
	 * @return sql���
	 */
	public static String createStatement(EntityConfig dc, Class<?> entity, String entityId, int method)
			throws Exception
	{
		StringBuffer sb = new StringBuffer();
		switch (method)
		{
			case SQLUtil.ENTITY_SELECT:
				sb.append("SELECT * FROM ");
				sb.append(dc.getTableName());
				sb.append(" WHERE ");
				sb.append(dc.getPrimaryKey());
				sb.append(" = ");
				sb.append(SQLUtil.createKeyStatement(dc, entity, entityId));
				break;
			case SQLUtil.ENTITY_SELECT_FOR_UPDATE:
				sb.append("SELECT * FROM ");
				sb.append(dc.getTableName());
				sb.append(" WITH(UPDLOCK, ROWLOCK) WHERE ");
				sb.append(dc.getPrimaryKey());
				sb.append(" = ");
				sb.append(SQLUtil.createKeyStatement(dc, entity, entityId));
				break;
			case SQLUtil.ENTITY_DELETE:
				sb.append("DELETE FROM ");
				sb.append(dc.getTableName());
				sb.append(" WHERE ");
				sb.append(dc.getPrimaryKey());
				sb.append(" = ");
				sb.append(SQLUtil.createKeyStatement(dc, entity, entityId));
				break;
			case SQLUtil.ENTITY_COUNT:
				sb.append("SELECT COUNT(*) FROM ");
				sb.append(dc.getTableName());
				sb.append(" WHERE ");
				sb.append(dc.getPrimaryKey());
				sb.append(" = ");
				sb.append(SQLUtil.createKeyStatement(dc, entity, entityId));
				break;
			default:
				throw new Exception("��֧�ֵ��������.");
		}
		logger.debug(sb);
		return sb.toString();
	}

	/**
	 * <pre>
	 * ���SQL���
	 * </pre>
	 * @param dc ������
	 * @param entity ʵ�����
	 * @param method ��ɾ�Ĳ�
	 * @return sql���
	 */
	public static String createStatement(EntityConfig dc, Object entity, int method) throws Exception
	{
		StringBuffer sb = new StringBuffer();
		switch (method)
		{
			case SQLUtil.ENTITY_INSERT:
				sb.append("INSERT INTO ");
				sb.append(dc.getTableName());
				sb.append(SQLUtil.createInsertStatement(dc, entity));
				break;
			case SQLUtil.ENTITY_SELECT:
				sb.append("SELECT * FROM ");
				sb.append(dc.getTableName());
				sb.append(" WHERE ");
				sb.append(dc.getPrimaryKey());
				sb.append(" = ");
				sb.append(SQLUtil.createKeyStatement(dc, entity));
				break;
			case SQLUtil.ENTITY_SELECT_FOR_UPDATE:
				sb.append("SELECT * FROM ");
				sb.append(dc.getTableName());
				sb.append(" WITH(UPDLOCK, ROWLOCK) WHERE ");
				sb.append(dc.getPrimaryKey());
				sb.append(" = ");
				sb.append(SQLUtil.createKeyStatement(dc, entity));
				break;
			case SQLUtil.ENTITY_UPDATE:
				sb.append("UPDATE ");
				sb.append(dc.getTableName());
				sb.append(" SET ");
				sb.append(SQLUtil.createUpdateStatement(dc, entity));
				sb.append(" WHERE ");
				sb.append(dc.getPrimaryKey());
				sb.append(" = ");
				sb.append(SQLUtil.createKeyStatement(dc, entity));
				break;
			case SQLUtil.ENTITY_DELETE:
				sb.append("DELETE FROM ");
				sb.append(dc.getTableName());
				sb.append(" WHERE ");
				sb.append(dc.getPrimaryKey());
				sb.append(" = ");
				sb.append(SQLUtil.createKeyStatement(dc, entity));
				break;
			case SQLUtil.ENTITY_COUNT:
				sb.append("SELECT COUNT(*) AS count FROM ");
				sb.append(dc.getTableName());
				sb.append(" WHERE ");
				sb.append(dc.getPrimaryKey());
				sb.append(" = ");
				sb.append(SQLUtil.createKeyStatement(dc, entity));
				break;
			case SQLUtil.ENTITY_SAVE_OR_UPDATE:
				if (SQLUtil.getEntityPrimaryKeyValue(dc, entity) != null)
				{
					sb.append("IF NOT EXISTS(" + SQLUtil.createStatement(dc, entity, SQLUtil.ENTITY_SELECT) + ") ");
					sb.append(SQLUtil.createStatement(dc, entity, SQLUtil.ENTITY_INSERT));
					sb.append(" ELSE ");
					sb.append(SQLUtil.createStatement(dc, entity, SQLUtil.ENTITY_UPDATE));
				}
				else
				{
					sb.append(SQLUtil.createStatement(dc, entity, SQLUtil.ENTITY_INSERT));
				}
				break;
			default:
				throw new Exception("��֧�ֵ��������.");
		}
		logger.debug(sb);
		return sb.toString();
	}

	/**
	 * <pre>
	 * ���ͳ�Ʊ��¼��SQL���
	 * </pre>
	 * @param dc ������
	 * @param filter ������䣬ǰ�治��WHERE
	 * @return sql���
	 */
	public static String createCountStatement(EntityConfig dc, String filter) throws Exception
	{
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT COUNT(1) AS count FROM ");
		sb.append(dc.getTableName());
		if ((filter != null) && (!"".equals(filter)))
		{
			sb.append(" WHERE ");
			sb.append(filter);
		}
		logger.debug(sb);
		return sb.toString();
	}

	/**
	 * <pre>
	 * ���ͳ�Ʊ��¼��SQL���
	 * </pre>
	 * @param tableName ����
	 * @param filter ������䣬ǰ�治��WHERE
	 * @return sql���
	 */
	public static String createCountStatement(String tableName, String filter) throws Exception
	{
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT COUNT(1) AS count FROM ");
		sb.append(tableName);
		if ((filter != null) && (!"".equals(filter)))
		{
			sb.append(" WHERE ");
			sb.append(filter);
		}
		logger.debug(sb);
		return sb.toString();
	}

	/**
	 * <pre>
	 * ��ɸ�������ֶβ���
	 * </pre>
	 * @param dc ������
	 * @param entity ʵ�����
	 * @return �ֶβ������
	 */
	public static String createUpdateStatement(EntityConfig dc, Object entity) throws Exception
	{
		try
		{
			StringBuffer fieldValue = new StringBuffer();
			Method[] methods = entity.getClass().getMethods();
			SimpleDateFormat timeStampFormt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
			for (int i = 0; i < methods.length; i++)
			{
				Method method = methods[i];
				String fieldName = method.getName().substring(3);
				if (!fieldName.equalsIgnoreCase(dc.getPrimaryKey()))
				{
					if ((!method.getDeclaringClass().equals(Object.class)) && (method.getName().startsWith("get")))
					{
						Class<?> rtnType = method.getReturnType();
						Object value = method.invoke(entity);
						if (value != null)
						{
							if (rtnType.equals(java.lang.String.class))
							{
								fieldValue.append(" ").append(fieldName).append(" = '").append(value.toString())
										.append("',");
							}
							else if (rtnType.equals(java.util.Date.class))
							{
								fieldValue.append(" ").append(fieldName).append(" = '").append(
										timeStampFormt.format((Date) value)).append("',");
							}
							else
							{
								fieldValue.append(" ").append(fieldName).append(" = ").append(value.toString()).append(
										",");
							}
						}
					}
				}
			}
			return fieldValue.substring(0, fieldValue.length() - 1);
		}
		catch (SecurityException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
		catch (IllegalArgumentException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
		catch (IllegalAccessException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
		catch (InvocationTargetException e)
		{
			throw new Exception("��ȡʵ������ʱ�쳣.", e);
		}
	}

	/**
	 * <pre>
	 * ���ʵ��������Ϣ��װ��ҳ�Ĳ�ѯ���
	 * ע��:ʹ����TOP+MIN/MAX��
	 * </pre>
	 * @param dc ʵ��������Ϣ
	 * @param whereClause ɸѡ����,����name = 'xxx' And gender=1
	 * @param pageSize ÿҳ��ʾ��¼��
	 * @param pageIndex ��ǰҳ��
	 * @return ��ҳ��SQL���
	 */
	public static final String assembleFastPaginationSQLByEntity(EntityConfig dc, String whereClause, int pageSize,
			int pageIndex)
	{
		return SQLUtil.assembleFastPaginationSQL(dc.getTableName(), "*", whereClause, dc.getPrimaryKey(), false,
				pageSize, pageIndex);
	}

	/**
	 * <pre>
	 * ��װ��ҳ�Ĳ�ѯ���
	 * ע��:ʹ����TOP+MIN/MAX, Ҫ��orderFieldName�ֶ�Ϊ������߾���ΨһԼ��
	 * </pre>
	 * @param tableName ����
	 * @param getFieldNames ѡȡ������,����:name,gender...
	 * @param whereClause ɸѡ����,����name = 'xxx' And gender=1
	 * @param orderFieldName �����ֶ�,����seqNo
	 * @param isOrderAsc �Ƿ�����
	 * @param pageSize ÿҳ��ʾ��¼��
	 * @param pageIndex ��ǰҳ��
	 * @return ��ҳ��SQL���
	 */
	public static final String assembleFastPaginationSQL(String tableName, String getFieldNames, String whereClause,
			String orderFieldName, boolean isOrderAsc, int pageSize, int pageIndex)
	{
		String pageTempString = null;
		String tempOrderString = null;
		if ((getFieldNames == null) || ("".equals(getFieldNames)))
		{
			getFieldNames = "*";
		}

		if (isOrderAsc)
		{
			pageTempString = " > ( SELECT MAX ";
			tempOrderString = " ORDER BY [" + orderFieldName + "] ASC";
		}
		else
		{
			pageTempString = " < ( SELECT MIN ";
			tempOrderString = " ORDER BY [" + orderFieldName + "] DESC";
		}

		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append(" SELECT TOP " + pageSize + " " + getFieldNames + "  FROM [" + tableName + "] ");
		if (pageIndex == 1)
		{
			if ((whereClause != null) && (!"".equals(whereClause)))
			{
				sqlBuffer.append(" WHERE ");
				sqlBuffer.append(whereClause);
				sqlBuffer.append(" ");
				sqlBuffer.append(tempOrderString);
			}
			else
			{
				sqlBuffer.append(tempOrderString);
			}
		}
		else
		{
			sqlBuffer.append(" WHERE [");
			sqlBuffer.append(orderFieldName);
			sqlBuffer.append("] ");
			sqlBuffer.append(pageTempString);
			sqlBuffer.append("([");
			sqlBuffer.append(orderFieldName);
			sqlBuffer.append("]) FROM (SELECT TOP  ");
			sqlBuffer.append((pageIndex - 1) * pageSize);
			sqlBuffer.append(" [");
			sqlBuffer.append(orderFieldName);
			sqlBuffer.append("] FROM [");
			sqlBuffer.append(tableName);
			if ((whereClause != null) && (!"".equals(whereClause)))
			{
				sqlBuffer.append("] WHERE ");
				sqlBuffer.append(whereClause);
				sqlBuffer.append(" ");
				sqlBuffer.append(tempOrderString);
				sqlBuffer.append(" ) AS tblTmp) AND ");
				sqlBuffer.append(whereClause);
				sqlBuffer.append(" ");
			}
			else
			{
				sqlBuffer.append("] ");
				sqlBuffer.append(tempOrderString);
				sqlBuffer.append(" ) AS tblTmp) ");
			}
			sqlBuffer.append(tempOrderString);
		}
		logger.debug(sqlBuffer);
		return sqlBuffer.toString();
	}

	/**
	 * <pre>
	 * ���ʵ��������Ϣ��װ��ҳ�Ĳ�ѯ���
	 * </pre>
	 * @param dc ʵ��������Ϣ
	 * @param whereClause ɸѡ����,����name = 'xxx' And gender=1
	 * @param pageSize ÿҳ��ʾ��¼��
	 * @param pageIndex ��ǰҳ��
	 * @return ��ҳ��SQL���
	 */
	public static final String assemblePaginationSQLByEntity(EntityConfig dc, String whereClause, int pageSize,
			int pageIndex)
	{
		return SQLUtil.assemblePaginationSQL(dc.getTableName(), dc.getPrimaryKey(), "*", whereClause, null, false,
				pageSize, pageIndex);
	}

	/**
	 * <pre>
	 * ���ʵ��������Ϣ��װ��ҳ�Ĳ�ѯ���
	 * </pre>
	 * @param dc ʵ��������Ϣ
	 * @param whereClause ɸѡ����,����name = 'xxx' And gender=1
	 * @param orderFieldName �����ֶ�,����seqNo
	 * @param isOrderAsc �Ƿ�����
	 * @param pageSize ÿҳ��ʾ��¼��
	 * @param pageIndex ��ǰҳ��
	 * @return ��ҳ��SQL���
	 */
	public static final String assemblePaginationSQLByEntity(EntityConfig dc, String whereClause,
			String orderFieldName, boolean isOrderAsc, int pageSize, int pageIndex)
	{
		return SQLUtil.assemblePaginationSQL(dc.getTableName(), dc.getPrimaryKey(), "*", whereClause, orderFieldName,
				isOrderAsc, pageSize, pageIndex);
	}

	/**
	 * <pre>
	 * ��װ��ҳ�Ĳ�ѯ���
	 * </pre>
	 * @param tableName ����
	 * @param primaryKey �������
	 * @param getFieldNames ѡȡ������,����:name,gender...
	 * @param whereClause ɸѡ����,����name = 'xxx' And gender=1
	 * @param orderFieldName �����ֶ�,����seqNo
	 * @param isOrderAsc �Ƿ�����
	 * @param pageSize ÿҳ��ʾ��¼��
	 * @param pageIndex ��ǰҳ��
	 * @return ��ҳ��SQL���
	 */
	public static final String assemblePaginationSQL(String tableName, String primaryKey, String getFieldNames,
			String whereClause, String orderFieldName, boolean isOrderAsc, int pageSize, int pageIndex)
	{
		String orderString = null;
		if ((getFieldNames == null) || ("".equals(getFieldNames)))
		{
			getFieldNames = "*";
		}

		if ((orderFieldName == null) || ("".equals(orderFieldName)))
		{
			orderString = "";
		}
		else
		{
			if (isOrderAsc)
			{
				orderString = " ORDER BY [" + orderFieldName + "] ASC";
			}
			else
			{
				orderString = " ORDER BY [" + orderFieldName + "] DESC";
			}
		}

		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append(" SELECT TOP " + pageSize + " " + getFieldNames + "  FROM [" + tableName + "] ");
		if (pageIndex == 1)
		{
			if ((whereClause != null) && (!"".equals(whereClause)))
			{
				sqlBuffer.append(" WHERE ");
				sqlBuffer.append(whereClause);
				sqlBuffer.append(" ");
			}
			sqlBuffer.append(orderString);
		}
		else
		{
			sqlBuffer.append(" WHERE NOT EXISTS (SELECT ");
			sqlBuffer.append(getFieldNames);
			sqlBuffer.append(" FROM ( SELECT TOP  ");
			sqlBuffer.append((pageIndex - 1) * pageSize);
			sqlBuffer.append(" ");
			sqlBuffer.append(getFieldNames);
			sqlBuffer.append(" FROM [");
			sqlBuffer.append(tableName);
			if ((whereClause != null) && (!"".equals(whereClause)))
			{
				sqlBuffer.append("] WHERE ");
				sqlBuffer.append(whereClause);
				sqlBuffer.append(" ");
				sqlBuffer.append(orderString);
				sqlBuffer.append(" ) AS tblTmp WHERE tblTmp.");
				sqlBuffer.append(primaryKey);
				sqlBuffer.append(" = ");
				sqlBuffer.append(tableName);
				sqlBuffer.append(".");
				sqlBuffer.append(primaryKey);
				sqlBuffer.append(" ) AND ");
				sqlBuffer.append(whereClause);
				sqlBuffer.append(" ");
			}
			else
			{
				sqlBuffer.append("] ");
				sqlBuffer.append(orderString);
				sqlBuffer.append(" ) AS tblTmp WHERE tblTmp.");
				sqlBuffer.append(primaryKey);
				sqlBuffer.append(" = ");
				sqlBuffer.append(tableName);
				sqlBuffer.append(".");
				sqlBuffer.append(primaryKey);
				sqlBuffer.append(") ");
			}
			sqlBuffer.append(orderString);
		}
		logger.debug(sqlBuffer);
		return sqlBuffer.toString();
	}

	/**
	 * <pre>
	 * ����ݼ�ת��Ϊʵ�弯��
	 * </pre>
	 * @param rs ��ݼ�
	 * @param entityClass ʵ������
	 * @return ʵ�弯��
	 * @throws Exception ��ݿ��쳣
	 */
	public static <T> List<T> rs2Entity(ResultSet rs, Class<T> entityClass) throws Exception
	{
		List<T> list = new ArrayList<T>();
		try
		{
			Method[] methods = entityClass.getMethods();
			while (rs != null && rs.next())
			{
				T object = entityClass.newInstance();
				for (int i = 0; i < methods.length; i++)
				{
					Method method = methods[i];
					Object value = null;
					if (method.getName().startsWith("set"))
					{
						String fieldName = method.getName().substring(3);
						value = rs.getObject(fieldName);
						if (value != null)
						{
							try
							{
								method.invoke(object, new Object[] { value });
							}
							catch (Exception e)
							{
								logger.warn("ʵ��־û����ʱ�쳣{" + e.getMessage() + "},ʵ������{"
										+ object.getClass().getName() + "} ������{" + method.getName()
										+ "}, jdbc��������{" + value.getClass().getName() + "}, ������.");
							}
						}
					}
				}
				list.add(object);
			}
		}
		catch (InstantiationException e)
		{
			throw new Exception("ʵ��־û����ʱ�쳣", e);
		}
		catch (IllegalAccessException e)
		{
			throw new Exception("ʵ��־û����ʱ�쳣", e);
		}
		catch (SQLException e)
		{
			throw new Exception("ʵ��־û����ʱ�쳣", e);
		}
		catch (IllegalArgumentException e)
		{
			throw new Exception("ʵ��־û����ʱ�쳣", e);
		}
		return list;
	}

	/**
	 * <pre>
	 * ����ݼ�ת��Ϊ����ݼ���
	 * </pre>
	 * @param rs ��ݼ�
	 * @return ����ݼ���
	 * @throws Exception ��ݿ��쳣
	 */
	public static List<List<Object>> rs2List(ResultSet rs) throws Exception
	{
		List<List<Object>> list = new ArrayList<List<Object>>();
		try
		{
			if (rs != null)
			{
				int columnCount = rs.getMetaData().getColumnCount();
				while (rs.next())
				{
					List<Object> rowList = new ArrayList<Object>();
					for (int i = 0; i < columnCount; i++)
					{
						Object columnValue = rs.getObject(i + 1);
						rowList.add(columnValue);
					}
					list.add(rowList);
				}
			}
		}
		catch (SQLException e)
		{
			throw new Exception("ʵ��־û����ʱ�쳣", e);
		}
		return list;
	}

	/**
	 * <pre>
	 * ����ݼ�ת��Ϊʵ�弯��
	 * </pre>
	 * @param map ��ݼ�
	 * @param entityClass ʵ������
	 * @return ʵ�弯��
	 * @throws Exception ��ݿ��쳣
	 * @deprecated ��ʹ��{@link #SqlRowSet2List(SqlRowSet, Class)}���
	 */
	public static <T> T Map2Entity(Map<Object, Object> map, Class<T> entityClass) throws Exception
	{
		try
		{
			Map<Object, Object> newMap = new HashMap<Object, Object>();
			for (Iterator<Entry<Object, Object>> iter = map.entrySet().iterator(); iter.hasNext();)
			{
				Entry<Object, Object> element = (Entry<Object, Object>) iter.next();
				newMap.put("set" + element.getKey().toString().toLowerCase(), element.getValue());
			}
			map.clear();
			map = null;

			Method[] methods = entityClass.getMethods();
			T object = entityClass.newInstance();
			for (int i = 0; i < methods.length; i++)
			{
				Method method = methods[i];
				Object value = null;
				if (method.getName().startsWith("set"))
				{
					value = newMap.get(method.getName().toLowerCase());
					if (value != null)
					{
						try
						{
							method.invoke(object, new Object[] { value });
						}
						catch (InvocationTargetException e)
						{
							logger.warn("ʵ��־û����ʱ�쳣{" + e.getMessage() + "},ʵ������{" + object.getClass().getName()
									+ "} ������{" + method.getName() + "}, jdbc��������{" + value.getClass().getName()
									+ "}, ������.");
						}
						catch (IllegalAccessException e)
						{
							logger.error("ʵ��־û����ʱ�쳣{" + e.getMessage() + "},ʵ������{" + object.getClass().getName()
									+ "} ������{" + method.getName() + "}, jdbc��������{" + value.getClass().getName()
									+ "}, ������.");
						}
						catch (IllegalArgumentException e)
						{
							logger.error("ʵ��־û����ʱ�쳣{" + e.getMessage() + "},ʵ������{" + object.getClass().getName()
									+ "} ������{" + method.getName() + "}, jdbc��������{" + value.getClass().getName()
									+ "}, ������.");
						}
					}
				}

			}

			return object;
		}
		catch (InstantiationException e)
		{
			throw new Exception("ʵ��־û����ʱ�쳣", e);
		}
		catch (IllegalAccessException e)
		{
			throw new Exception("ʵ��־û����ʱ�쳣", e);
		}
	}

	/**
	 * <pre>
	 * ���м�¼��ݼ�ת��Ϊʵ�弯��
	 * </pre>
	 * @param set �м�¼��ݼ�
	 * @param entityClass ʵ������
	 * @return ʵ�弯��
	 * @throws Exception ��ݿ��쳣
	 */
	public static <T> List<T> SqlRowSet2List(SqlRowSet set, Class<T> entityClass) throws Exception
	{
		List<T> list = new ArrayList<T>();
		try
		{
			if (set != null)
			{
				String[] columnNames = set.getMetaData().getColumnNames();
				Set<String> columnNameSet = new HashSet<String>();
				for (int i = 0; i < columnNames.length; i++)
				{
					columnNameSet.add(columnNames[i].toLowerCase());
				}

				while (set.next())
				{
					Method[] methods = entityClass.getMethods();
					T object = entityClass.newInstance();
					for (int i = 0; i < methods.length; i++)
					{
						Method method = methods[i];
						Object value = null;
						if (method.getName().startsWith("set"))
						{
							String propertyName = method.getName().substring(3).toLowerCase();
							if (columnNameSet.contains(propertyName))
							{
								value = set.getObject(propertyName);
								if (value != null)
								{
									try
									{
										method.invoke(object, new Object[] { value });
									}
									catch (Exception e)
									{
										logger.error("ʵ��־û����ʱ�쳣{" + e.getMessage() + "},ʵ������{"
												+ object.getClass().getName() + "}, ������{" + method.getName()
												+ "}, jdbc��������{" + value.getClass().getName() + "}, ������.");
									}
								}
							}
						}

					}
					list.add(object);
				}
			}
		}
		catch (InvalidResultSetAccessException e)
		{
			throw new Exception("ʵ��־û����ʱ�쳣", e);
		}
		return list;
	}
}
